import TableData from "@/components/public/el-table"; //主页面列表
import messageBox from "@/components/public/messageBox"; //弹框
import TableLyout from '@/components/commonPublic/tableLyout.vue'
import {
    getSampleWorkWebList, //列表页接口
    getfSampletype, //获取样品种类
    submitSampleWork, //提交
    delSampleWork, //删除
    copysaveSampleWork, //复制
    rollBackSample
} from "@/api/request.js";

import publicForm from "@/components/materialDataManage/fromCom.vue"; //弹框form
import formJs from "./regexDetail.js"; //新增弹框配置
import actions from "@/actions";
import API from '@/utils/commonRequest.js'


export default {
    name: "fieldSampling",
    data() {
        return {
            name: "fieldSampling",
            userNature: null, //用户Nature
            // 弹框
            showMsgBox: false,
            msgTip: "请先选中数据行！",
            msgType: 1,
            // 弹框
            projectsObj: [], //项目名
            tendersObj: [],
            falgId: null,

            isLock: false,
            projectId: null,
            projectName: null,
            loading: false,
            btnObj: formJs.btnObj, //按钮
            queryCriteriaData: {}, //分页
            searchObj: formJs.searchObj, //搜索条件
            table_config: formJs.table_config, //列表

            // 列表
            getList: {
                fprojectid: "",
                fCompanyid: "", //左侧选中组织机构id
                fSamplemodel: "", // 上方查询条件样品种类  对应code
                fSamplename: "", // 上方查询条件样品名称
                fStatus: "", // 上方查询条件样品状态
                keyType: "", // 上方查询条件样品种类
                taskNumber: "", // 上方查询条件进场编号
                page: 1, //当前页码
                pageSize: 15, //每页显示条数
                userId: "", //查询待办或已办时传 列表页查询不传
                modelType: 6, //0-待办 1-已办 传2 表示列表页查询
                startDates: "", //取样日期开始时间
                endDates: "", //取样日期结束时间
                timeDates: [],
                fSamplenostr: ""
            },
            isShow: false, //是否显示弹框
            statusNum: null, //点击那个按钮
            dataFid: null, //列表详情id
            currentRow: null, //列表详情
            activeIndex: "1",
            fId: null, //当前数据fId
            tableData: [],
            companyId: null,
            currentRowId: "",
            dialogTitle: null,

        };
    },
    components: {
        TableLyout,
        publicForm,
        TableData,
        messageBox

    },
    mounted() {
        API.userNature().then((res) => {
            if (res.errcode == 0) {
                this.userNature = res.data.Nature;
            }
        }).catch((err) => {
            console.log("API", err)
        })
        actions.onGlobalStateChange((state, prev) => {
            var data = prev.currentUser.projects;
            this.userInfo = prev.currentUser;
        }, true);

        this.getfSampletypeFun(); //样品种类
        this.getDate();

        this.table_config.operation.cols = [{
            prop: "fStatus",
            type: "primary",
            handleRow: this.handleRow,
        }, ];
        this.table_config.operation["specialClass"] = function (rowData) {
            var color = null;
            if (rowData == "待取样") {
                color = "red !important";
            } else if (rowData == "待收样") {
                color = "orange !important";
            } else if (rowData == "已收样") {
                color = "green !important";
            } else {
                color = "#409eff !important";
            }
            return color;
        };

    },
    destroyed() {},
    methods: {
        confirmMsg() {
            this.showMsgBox = false;
        },
        // 带功能确定
        confirmMsgs() {
            this.showMsgBox = false;
            if (this.titelName == "提交") {
                this.yj_submit();
            } else if (this.titelName == "删除") {
                this.yj_delete();
            } else if (this.titelName == "复制") {
                this.yj_copy();
            } else if (this.titelName == "撤销") {
                this.yj_return(this.currentRow);
            }
        },
        reset(e) {
            this.getList = this.$options.data.call(this).getList;
            this.getList.fprojectid = e;
        },
        getBtnName(name, status) {
            this.statusNum = status
            this.yj_edit(status);
        },
        handleNode(data, status) {
            if (status != 0) {
                this.getList.fSamplemodel = data.fSampletypename; //样品种类汉字
            } else {
                this.getList.fSamplemodel = ""; //样品种类汉字

            }
            // console.log("handleNode", data);

        },

        // 新增/编辑
        yj_edit(num) {
            this.msgType = 1; // 0 带功能确定  1 无功能确定  2 带功能确定、取消
            var data;

            if (num == 7) { //查看
                if (this.dataFid != null) {
                    this.$router.push({
                        path: "/sampleManage/fieldSamplingText",
                    });
                    data = {
                        data: this.currentRow,
                        getList: this.getList,
                        status: num,
                        displaySwitching: 2,
                        changeBtn: true,
                        fprojectid: this.getList.fprojectid,
                        fCompanyid: this.getList.fCompanyid,
                    }
                } else {
                    this.$message.warning({
                        content: "请先选择需要查看的数据",
                        duration: 1000
                    })
                }
            } else if (num == 9) {
                if (this.dataFid != null) {
                    if (this.currentRow.fStatus == '已收样') {
                        this.revokeText();

                    } else {

                        this.$message.warning({
                            content: '当前数据不可撤销',
                            duration: 1000
                        });
                    }

                } else {

                    this.$message.warning({
                        content: '请先选择需要撤销的数据',
                        duration: 1000
                    });
                }
            }
            if (num == 10) {
                if (this.dataFid != null) {
                    if (this.currentRow.fStatus == '待收样') {
                        this.yj_return(this.currentRow, '撤回');

                    } else {

                        this.$message.warning({
                            content: '请选择样品状态为"待收样"的数据！',
                            duration: 1000
                        })
                    }

                } else {

                    this.$message.warning({
                        content: "请先选择需要撤回的数据",
                        duration: 1000
                    })
                }
            } else {
                var that = this;
                if (num == 1) { // 新增
                    if (that.userNature == '施工单位' || that.userNature == '中心试验室') {
                        if (that.getList.fCompanyid != "" && that.getList.fCompanyid != null && that.getList.fprojectid != "" && that.getList.fprojectid != null) {
                            that.$router.push({
                                path: "/sampleManage/fieldSamplingText",
                            });
                            data = {
                                data: "",
                                getList: that.getList,
                                status: num,
                                displaySwitching: 0,
                                changeBtn: false,
                                fprojectid: this.getList.fprojectid,
                                fCompanyid: this.getList.fCompanyid,
                            }
                        } else {
                            that.$message.warning({
                                content: "请先选择项目名称和标段名称",
                                duration: 1000
                            })
                        }
                    } else {
                        that.$message.warning({
                            content: "该用户无法操作",
                            duration: 1000
                        })
                    }
                } else if (num == 2) { // 编辑
                    if (that.dataFid != null && that.currentRow.fStatus == '待取样') {
                        if (that.userNature == '施工单位') {
                            if (that.currentRow.fChecktype == "施工自检" || that.currentRow.fChecktype == "施工外委") {
                                that.$router.push({
                                    path: "/sampleManage/fieldSamplingText",
                                });
                                data = {
                                    data: that.currentRow,
                                    getList: that.getList,
                                    status: num,
                                    displaySwitching: 0,
                                    changeBtn: false,
                                    fprojectid: this.getList.fprojectid,
                                    fCompanyid: this.getList.fCompanyid,
                                }
                            } else {
                                that.$message.warning({
                                    content: "当前用户不可编辑本条数据！",
                                    duration: 1000
                                })
                            }
                        } else if (that.userNature == '中心试验室') {
                            if (that.currentRow.fChecktype == "监理抽检" || that.currentRow.fChecktype == "监理外委") {
                                that.$router.push({
                                    path: "/sampleManage/fieldSamplingText",
                                });
                                data = {
                                    data: that.currentRow,
                                    getList: that.getList,
                                    status: num,
                                    displaySwitching: 0,
                                    changeBtn: false,
                                    fprojectid: this.getList.fprojectid,
                                    fCompanyid: this.getList.fCompanyid,
                                }
                            } else {
                                that.$message.warning({
                                    content: "当前用户不可编辑本条数据！",
                                    duration: 1000
                                })
                            }
                        } else {
                            that.$message.error({
                                content: "该用户无法操作!",
                                duration: 1000
                            })
                        }
                    } else {
                        that.$message.warning({
                            content: "请先选择需要编辑的数据,且样品状态为'待取样'",
                            duration: 1000
                        })
                    };
                } else if (num == 3) { //提交
                    if (that.dataFid != null) {
                        if (that.currentRow.fStatus == '待取样' && that.currentRow.fSampleperson != "" && that.currentRow.fSampleperson != null) {
                            if (that.userNature == '施工单位') {
                                if (that.currentRow.fChecktype == "施工自检" || that.currentRow.fChecktype == "施工外委") {
                                    that.SubmitText();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可提交本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else if (that.userNature == '中心试验室') {
                                if (that.currentRow.fChecktype == "监理抽检" || that.currentRow.fChecktype == "监理外委") {
                                    that.SubmitText();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可提交本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else {
                                that.$message.error({
                                    content: "该用户无法操作!",
                                    duration: 1000
                                })
                            }
                        } else {
                            that.$message.warning({
                                content: '请选择样品状态为"待取样"且取样人不为空的数据！',
                                duration: 1000
                            })
                        }
                    } else {
                        that.$message.warning({
                            content: '请先选择需要提交的数据',
                            duration: 1000
                        })
                    }
                } else if (num == 4) { //删除
                    if (that.dataFid != null) {
                        if (that.currentRow.fStatus == '待取样') {
                            if (that.userNature == '施工单位') {
                                if (that.currentRow.fChecktype == "施工自检" || that.currentRow.fChecktype == "施工外委") {
                                    that.rowDelete();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可删除本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else if (that.userNature == '中心试验室') {
                                if (that.currentRow.fChecktype == "监理抽检" || that.currentRow.fChecktype == "监理外委") {
                                    that.rowDelete();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可删除本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else {
                                that.$message.error({
                                    content: "该用户无法操作!",
                                    duration: 1000
                                })
                            }
                        } else {
                            that.$message.warning({
                                content: '请选择样品状态为"待取样"的数据！',
                                duration: 1000
                            })
                        }
                    } else {
                        that.$message.warning({
                            content: '请先选择需要删除的数据',
                            duration: 1000
                        })

                    }
                } else if (num == 5) { //导出
                    var id;
                    if (this.getList.fCompanyid != "") {
                        id = this.getList.fCompanyid;
                    } else {
                        id = this.getList.fprojectid;
                    }


                    // window.open("http://1.14.103.201:8300/IOTManagement/CLJC/getExcelByWTDLetterPageLists?fCompanyid=" + id + "&keyType" + this.getList.keyType + "&taskNumber=" + this.getList.taskNumber + "&startDates=" + this.getList.startDates+ "&endDates=" + this.getList.endDates);

                    that.$message.warning({
                        content: "导出功能暂未开放",
                        duration: 1000
                    })
                } else if (num == 6) { //复制
                    if (that.dataFid != null) {
                        if (that.currentRow.fStatus == '待取样') {
                            if (that.userNature == '施工单位') {
                                if (that.currentRow.fChecktype == "施工自检" || that.currentRow.fChecktype == "施工外委") {
                                    that.CopyText();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可复制本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else if (that.userNature == '中心试验室') {
                                if (that.currentRow.fChecktype == "监理抽检" || that.currentRow.fChecktype == "监理外委") {
                                    that.CopyText();
                                } else {
                                    that.$message.warning({
                                        content: "当前用户不可复制本条数据！",
                                        duration: 1000
                                    })
                                }
                            } else {
                                that.$message.error({
                                    content: "该用户无法操作!",
                                    duration: 1000
                                })
                            }
                        } else {
                            that.$message.warning({
                                content: '请选择样品状态为"待取样"的数据！',
                                duration: 1000
                            })
                        }
                    } else {
                        that.$message.warning({
                            content: '请先选择需要复制的数据',
                            duration: 1000
                        })
                    }
                }
            }
            sessionStorage.setItem("GxEmbedded_primaryInfo", JSON.stringify(data));
        },
        yj_return(row) {
            if (row.fId != "" && row.fId != null) {


                this.loading = true;
                rollBackSample({
                        fId: row.fId,
                        userId: this.userInfo.userId,
                        userName: this.userInfo.realName,
                    })
                    .then((res) => {
                        if (res.errcode == 0) {
                            this.loading = false;
                            this.yj_searchForm(this.getList);

                            this.$message.success({
                                content: "退回成功",
                                duration: 1000
                            });
                        } else {

                            this.$message.error({
                                content: "退回失败" + res.msg,
                                duration: 1000
                            });
                            this.loading = false;
                        }
                    })
                    .catch(() => {
                        console.log("退回失败");
                        this.loading = false;
                    });


            } else {
                return this.$message.error("请先选择需要撤销的数据");
            }
        },
        // 提交
        SubmitText() {
            this.msgTip = "是否继续提交?";
            this.msgType = 2; // 0 带功能确定  1 无功能确定  2 带功能确定、取消
            this.showMsgBox = true;
            this.titelName = "提交";
        },
        revokeText() {
            this.msgTip = "是否继续撤销?";
            this.msgType = 2; // 0 带功能确定  1 无功能确定  2 带功能确定、取消
            this.showMsgBox = true;
            this.titelName = "撤销";
        },
        yj_submit() {
            this.isLock = true
            this.loading = true;
            submitSampleWork({
                    fId: this.dataFid,
                    userId: this.userInfo.userId, //当前登录人id
                    userName: this.userInfo.realName //当前登录人姓名
                })
                .then((res) => {
                    if (res.errcode == 0) {
                        this.loading = false;
                        this.dataFid = null
                        this.isLock = false
                        this.yj_searchForm(this.getList);
                        this.$message.success({
                            content: "提交成功",
                            duration: 1000
                        });

                    } else {
                        this.isLock = false;
                        this.$message.error({
                            content: "提交失败" + res.msg,
                            duration: 1000
                        });
                        this.loading = false;
                        return false;
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    console.log("提交接口报错");
                });
        },
        // 复制
        CopyText() {
            this.msgTip = "是否继续复制?";
            this.msgType = 2; // 0 带功能确定  1 无功能确定  2 带功能确定、取消
            this.showMsgBox = true;
            this.titelName = "复制";
        },
        yj_copy() {
            this.isLock = true
            this.loading = true;
            copysaveSampleWork({
                    fId: this.dataFid,
                })
                .then((res) => {
                    if (res.errcode == 0) {
                        this.loading = false;
                        this.dataFid = null
                        this.isLock = false
                        this.yj_searchForm(this.getList);
                        this.$message.success({
                            content: "复制成功",
                            duration: 1000
                        });

                    } else {
                        this.isLock = false;
                        this.$message.error({
                            content: "复制失败" + res.msg,
                            duration: 1000
                        });
                        this.loading = false;
                        return false;
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    console.log("复制接口报错");
                });
        },

        // 删除
        rowDelete() {
            this.msgTip = "此操作将永久删除该数据, 是否继续?";
            this.msgType = 2; // 0 带功能确定  1 无功能确定  2 带功能确定、取消
            this.showMsgBox = true;
            this.titelName = "删除";
        },
        yj_delete() {
            this.isLock = true
            this.loading = true;
            delSampleWork({
                    fId: this.dataFid,
                    userId: this.userInfo.userId, //当前登录人id
                    userName: this.userInfo.realName //当前登录人姓名
                })
                .then((res) => {
                    if (res.errcode == 0) {
                        this.loading = false;
                        this.dataFid = null
                        this.isLock = false
                        this.yj_searchForm(this.getList);
                        this.$message.success({
                            content: "删除成功",
                            duration: 1000
                        })
                    } else {
                        this.isLock = false
                        this.$message.error({
                            content: "删除失败" + res.msg,
                            duration: 1000
                        })
                        this.loading = false;

                        return false;
                    }
                })
                .catch(() => {
                    this.loading = false;
                    console.log("删除接口报错");
                });
        },
        // 查看
        // 点击查看
        yj_viewForm(row, label) {
            this.currentRow = row;
            this.dataFid = row.fId;
            if (label == "样品名称") {
                this.yj_edit(7);
            }
        },
        // 点击当前行变色
        rowChange(val) {
            this.currentRow = val;
            this.dataFid = val.fId;
        },

        // 获取列表数据
        yj_searchForm(data) {
            window.sessionStorage.setItem(
                "GxEmbedded-sampleManage_getList",
                JSON.stringify(data)
            );
            var id;
            if (data.fCompanyid != "") {
                id = data.fCompanyid;
            } else {
                id = data.fprojectid;
            }
            var obj = {
                fCompanyid: id, //左侧选中组织机构id
                userId: this.userInfo.id, //查询待办或已办时传 列表页查询不传
                fSamplemodel: data.fSamplemodel, // 上方查询条件样品种类  对应code
                fSamplename: data.fSamplename, // 上方查询条件样品名称
                fStatus: data.fStatus, // 上方查询条件样品状态
                page: data.page, //当前页码
                pageSize: data.pageSize, //每页显示条数
                modelType: 6,
                startDates: data.startDates, //进场开始时间
                endDates: data.endDates, //进场结束时间
                fSamplenostr: data.fSamplenostr,
                fNature: this.userNature
            }
            this.loading = true;
            var that = this;
            getSampleWorkWebList(obj)
                .then((res) => {
                    if (res.errcode == 0) {
                        that.loading = false;
                        that.tableData = res.data.pageInfo.list;
                        this.queryCriteriaData = res.data.pageInfo;
                    } else {
                        this.$message.error({
                            content: "列表数据获取失败" + res.msg,
                            duration: 1000
                        })
                        this.loading = false;
                    }
                })
                .catch((error) => {
                    console.log("列表数据 接口出错" + error.msg);
                    this.loading = false;
                });
        },

        getDate() {
            if (JSON.parse(sessionStorage.getItem("GxEmbedded-sampleManage_getList"))) {
                var data = JSON.parse(sessionStorage.getItem("GxEmbedded-sampleManage_getList"));
                if (data.fprojectid != "") {
                    this.getTender(data.fprojectid);
                } else {
                    data.fprojectid = this.projectsObj[1].fItemValue;
                    this.getTender(data.fprojectid);
                }
                this.getList = {
                    fprojectid: data.fprojectid,
                    fCompanyid: data.fCompanyid, //左侧选中组织机构id
                    fSamplemodel: "", // 上方查询条件样品种类  对应code
                    fSamplename: "", // 上方查询条件样品名称
                    fStatus: "", // 上方查询条件样品状态
                    keyType: "", // 上方查询条件样品种类
                    taskNumber: "", // 上方查询条件进场编号
                    page: data.page, //当前页码
                    pageSize: 15, //每页显示条数
                    userId: this.userInfo.id, //查询待办或已办时传 列表页查询不传
                    modelType: 6,
                    startDates: data.startDates, //进场开始时间
                    endDates: data.endDates, //进场结束时间
                    timeDates: [data.startDates, data.endDates],
                    fSamplenostr: data.fSamplenostr
                };
            } else {
                this.getList.startDates = this.common.getDay(-90); // 开始时间
                this.getList.endDates = this.common.getDay(0); // 截至时间
                this.getList.timeDates = [this.getList.startDates, this.getList.endDates]
            }
        },

        // 筛选条件
        // 标段查询
        async getTender(e) {
            await this.$http(
                "http://172.18.5.31:8300/IOTManagement/Base/Company/getGXJLBaseCompanyList.do?projectId=" +
                e, {
                    headers: {
                        "Content-Type": "application/json",
                        Authorization: localStorage.getItem("access_token"),
                    },
                }
            ).then((res) => {
                if (res.status == 200) {
                    var data = res.data.data.GXCompanyList;
                    this.tendersObj = [];
                    if (data.length == 0) {
                        this.$message.warning({
                            content: "有其他人员登录此账号！",
                            duration: 1000,
                        });
                        setTimeout(() => {
                            window.location.href = "http://172.18.5.201:1080/login";
                        }, 1200);
                    } else if (data.length == 1) {
                        data.map((item) => {
                            this.tendersObj.push({
                                fItemName: item.sectionName,
                                fItemValue: item.sectionId,
                            });
                        });
                        this.getList.fCompanyid = data[0].sectionId;
                    } else {
                        this.tendersObj = [{
                            fItemName: "所有标段",
                            fItemValue: "",
                        }, ];
                        data.map((item) => {
                            this.tendersObj.push({
                                fItemName: item.sectionName,
                                fItemValue: item.sectionId,
                            });
                        });
                    }
                }
            });
        },
        // 标段变化
        selectCompanyid(e, index, prop) {
            console.log("selectCompanyid", e, index, prop);
        },
        // 下拉框树
        getfSampletypeFun() {
            var data = {
                fChecktypenum: "0", //0自检1外委
                fMaterialtypeid: "", //材料进场材料种类id
            };
            getfSampletype(data)
                .then((res) => {
                    if (res.errcode == 0) {
                        var arr = [{
                            children: [],
                            fParentId: "0",
                            fSamplemodel: "",
                            fSampletype: "0",
                            fSampletypename: "==请选择=="
                        }];
                        this.selectTreeData = arr.concat(this.tranListToTreeData(
                            res.data.SampletypeList
                        ));

                        this.searchObj[3].tree.treeData = this.selectTreeData;
                        this.searchObj[3].tree.checkData = [
                            this.selectTreeData[0].fSampletype,
                        ];
                    } else {
                        this.$message.error({
                            content: "获取样品种类" + res.msg,
                            duration: 1000
                        })
                        this.loadingEditDialog_cl = false;
                    }
                })
                .catch((error) => {
                    console.log("获取样品种类 接口出错", error.msg);
                    this.loadingEditDialog_cl = false;
                });
        },
        tranListToTreeData(data) {
            let result = [];
            if (!Array.isArray(data)) {
                return result;
            }
            // 清除已存在的数据  重新赋值
            data.forEach((item) => {
                delete item.children;
            });

            let map = {};
            data.forEach((item) => {
                map[item.fSampletype] = item;
            });

            data.forEach((item) => {
                let parent = map[item.fParentId];
                if (parent) {
                    (parent.children || (parent.children = [])).push(item);
                } else {
                    result.push(item);
                }
            });
            return result;
        },
        selectHandleNodeClick(data) {
            this.getList.fSamplemodel = data.fSampletypename; //样品种类汉字
        },
        // 下拉框树
        // 时间间隔
        selectTime(e) {
            if (e[0] != "" && e[1] != "") {
                this.getList.startDates = e[0] + " " + "00:00:00"; // 开始时间
                this.getList.endDates = e[1] + " " + "23:59:59"; // 截至时间
            } else {
                this.getList.startDates = ""; // 开始时间
                this.getList.endDates = ""; // 截至时间
            }
            this.getList.timeDates = [e[0], e[1]];
        },
        // 筛选条件
    },
};